package com.gopay.webtest.util;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

public abstract class BaseSign {
	
	private Map<String,List<String>> signMap = null;
	
	public Map<String,List<String>> getSignMap() {
		return signMap;
	}
	@Autowired
	public void setSignMap(Map<String,List<String>> signMap) {
		this.signMap = signMap;
	}
	
	public void sign(String tranCode, String signType, String signField, Object obj, HttpServletRequest request) throws Exception{
		if(tranCode == null || "".equals(tranCode))
			throw new Exception("交易码为空，无法进行加签处理");
		//get the sign list
		List<String> list = null;
		for (Map.Entry<String, List<String>> entry : signMap.entrySet()) {

			if(tranCode.equals(entry.getKey())){
				list = (List<String>)entry.getValue();
				break;
			}
		}
		
		if(list ==null || list.size()==0){
			throw new Exception("获取交易加签字段失败");
		}
		String signStrb = execute(obj,list);
		if(null == signStrb || "".equals(signStrb)){
			throw new Exception("组装加签明文失败");
		}
		
		System.out.println(signStrb);
		//根据内容加签方式进行加签
		String signTypeValue = null;
		if(obj instanceof Map) {
			signTypeValue = ((Map)obj).get(signType) == null? "":((Map)obj).get(signType).toString();
		}
		else
		    signTypeValue=	ReflectUtil.getFieldValue(obj,signType);

		//获得客户I的，方便多人测试api服务器证书
		String customerId = ReflectUtil.getFieldValue(obj,"customerId");
		if(customerId==null||"".equals(customerId)){
			customerId = ReflectUtil.getFieldValue(obj,"merchantID");
		}

		if(customerId==null||"".equals(customerId)){
			customerId = ReflectUtil.getFieldValue(obj,"merId");
		}
		//通过加签方式进行加签,增加一个参数，当前所属于那个环境
		String envName = (String) request.getSession().getAttribute("gopay_webtest_URL_Name");
		ApiUtil.setEnvName(envName);
		String signStra =SignUtil.sign(signStrb, signTypeValue,customerId,envName);
		
		//设置加签域
		ReflectUtil.setFieldValue(obj, signField, signStra);
		
		if(obj instanceof Map)
			((Map) obj).put(signField, signStra);
		
	}

	public String getSignStr(String tranCode,Object obj ) throws Exception{
		if(tranCode == null || "".equals(tranCode))
			throw new Exception("交易码为空，无法进行加签处理");
		//get the sign list
		List<String> list = null;
		for (Map.Entry<String, List<String>> entry : signMap.entrySet()) {

			if(tranCode.equals(entry.getKey())){
				list = (List<String>)entry.getValue();
				break;
			}
		}

		if(list ==null || list.size()==0){
			throw new Exception("获取交易加签字段失败");
		}
		String signStrb = execute(obj,list);
		if(null == signStrb || "".equals(signStrb)){
			throw new Exception("组装加签明文失败");
		}

		System.out.println(signStrb);
		return signStrb;

	}

	
	public abstract String execute(Object obj ,List<String> signFields) throws Exception;

}
